package com.szholly.pro.watergas_server.ps.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.ps.service.DomainService;
import com.szholly.pro.watergas_server.ps.service.ExceptionService;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.PageInfo;
import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/Exception/*")
public class ExceptionController extends BaseController {


	@Autowired
	ExceptionService exceptionService;
	@Autowired
	DomainService domainService;

	/**
	 * 获取异常数量
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getExceptionCount")
	public void getExceptionCount(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		int count = exceptionService.getAlarmProcessCount(params);
		JSONObject obj = new JSONObject();
		obj.put("count", count);
		outString(obj.toString());
	}

	/**
	 * 获取异常和缺失数据的标示和记录
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getExceptionList")
	public void getExceptionList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> map = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = exceptionService.getExceptionList(map, pageInfo);
		String result = DataUtil.listToJSONObject(list,null,pageInfo).toString();
		outString(result);
	}

	/**
	 * 导出异常记录表
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportDoc")
	public void exportDoc(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		Map<String, Object> root = new HashMap<String, Object>();
		List<RowBase> list = exceptionService.getExceptionList(params, null);
		root.put("list", list);
		
		String OUNAME = "";
		if (params.containsKey("station_id")) {
			OUNAME = commonService.getOperationUnitByStaionId(params.get("station_id"));
		} else if (params.containsKey("wwtp_id")) {
			OUNAME = commonService.getOperationUnit(params.get("wwtp_id"));
		}
		root.put("OUNAME", OUNAME);
		root.put("STATION_NAME", params.get("station_name"));

		outWord(root, "exceptions.xml", "异常和缺失数据的标识和说明记录表.doc");
	}

	/**
	 * 获取请求参数
	 * @return
	 */
	private Map<String, String> getParams() {
		Map<String, String> params = new HashMap<String, String>();
		String task_code = RequestUnit.getParameter("taskCode");
		if (StringUtil.IsNotNullOrEmpty(task_code)) {
			params.put("task_code", task_code);
		}
		String start = RequestUnit.getParameter("start");
		if (StringUtil.IsNotNullOrEmpty(start)) {
			params.put("start", start);
		}
		String end = RequestUnit.getParameter("end");
		if (StringUtil.IsNotNullOrEmpty(end)) {
			params.put("end", end);
		}
		String wwtp_id = RequestUnit.getParameter("WWTP_ID");
		if (StringUtil.IsNotNullOrEmpty(wwtp_id)) {
			params.put("wwtp_id", wwtp_id);
		}
		String water_type = RequestUnit.getParameter("WATER_TYPE");
		if (StringUtil.IsNotNullOrEmpty(water_type)) {
			params.put("water_type", water_type);
		}
		String flow_type = RequestUnit.getParameter("FLOW_TYPE");
		if (StringUtil.IsNotNullOrEmpty(flow_type)) {
			params.put("flow_type", flow_type);
		}
		String station_id = RequestUnit.getParameter("STATION_ID");
		if (StringUtil.IsNotNullOrEmpty(station_id)) {
			params.put("station_id", station_id);
		}
		String station_name = RequestUnit.getParameter("STATION_NAME");
		if (StringUtil.IsNotNullOrEmpty(station_name)) {
			params.put("station_name", station_name);
		}
		String alarm_type = RequestUnit.getParameter("ALARM_TYPE");
		if (StringUtil.IsNotNullOrEmpty(alarm_type)) {
			params.put("type", alarm_type);
		}
		String alarm_id = RequestUnit.getParameter("ALARM_ID");
		if (StringUtil.IsNotNullOrEmpty(alarm_id)) {
			params.put("alarm_id", alarm_id);
		}
		String is_popup = RequestUnit.getParameter("IS_POPUP");
		if (StringUtil.IsNotNullOrEmpty(is_popup)) {
			params.put("is_popup", is_popup);
		}
		String mobile_received = RequestUnit.getParameter("MOBILE_RECEIVED");
		if (StringUtil.IsNotNullOrEmpty(mobile_received)) {
			params.put("mobile_received", mobile_received);
		}
		String is_popup_not = RequestUnit.getParameter("IS_POPUP_NOT");
		if (StringUtil.IsNotNullOrEmpty(is_popup_not)) {
			params.put("is_popup_not", is_popup_not);
		}
		String mobile_received_not = RequestUnit.getParameter("MOBILE_RECEIVED_NOT");
		if (StringUtil.IsNotNullOrEmpty(mobile_received_not)) {
			params.put("mobile_received_not", mobile_received_not);
		}
		String status = RequestUnit.getParameter("STATUS");
		if (StringUtil.IsNotNullOrEmpty(status)) {
			status = StringUtil.joinForSQL(status.split(","), "','");
			params.put("status", status);
		}
		String CONTINUE_TIME = RequestUnit.getParameter("CONTINUE_TIME");
		if (StringUtil.IsNotNullOrEmpty(CONTINUE_TIME)) {
			status = StringUtil.joinForSQL(CONTINUE_TIME.split(","), "','");
			params.put("CONTINUE_TIME", CONTINUE_TIME);
		}
		String IS_RECOVER = RequestUnit.getParameter("IS_RECOVER");
		if (StringUtil.IsNotNullOrEmpty(IS_RECOVER)) {
			status = StringUtil.joinForSQL(IS_RECOVER.split(","), "','");
			params.put("IS_RECOVER", IS_RECOVER);
		}
		String alarm_datasource = RequestUnit.getParameter("ALARM_DATASOURCE");
		if (StringUtil.IsNotNullOrEmpty(alarm_datasource)) {
			params.put("alarm_datasource", alarm_datasource);
		}
		String alarmLogDate = RequestUnit.getParameter("alarmLogDate");
		if (StringUtil.IsNotNullOrEmpty(alarmLogDate)) {
			params.put("alarmLogDate", alarmLogDate);
		}
		String _format = RequestUnit.getParameter("_format");
		if (StringUtil.IsNotNullOrEmpty(_format)) {
			params.put("_format", _format);
		}
		return params;
	}
	
	@RequestMapping(value = "/getAlarmInfoType")
	public void getAlarmInfoType(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		List<RowBase> list = domainService.getDomain("ALARM_INFO_TYPE");
		//暂时隐藏日排放量异常、无数据这两项
		int n=0;
		int m=0;
		for(int i=0;i<list.size();i++){
			RowBase r=list.get(i);
			if(r.getSafeString("S_DOMAINCAPTION").contains("日排放量")){
				n=i;
			}
			if(r.getSafeString("S_DOMAINCAPTION").contains("无")){
				m=i;
			}
		}
		list.remove(m);
		list.remove(n);
		String result = DataUtil.listToJSONObject(list,null,null).toString();
		outString(result);
	}
	/**
	 * 获取新报警类型
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAlarmInfoTypeNew")
	public void getAlarmInfoTypeNew(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		List<RowBase> list = domainService.getDomain("报警类型");
		String result = DataUtil.listToJSONObject(list,null,null).toString();
		outString(result);
	}
	@RequestMapping(value = "/getAlarmInfoList")
	public void getAlarmInfoList(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = exceptionService.getAlarmInfoList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list,null,pageInfo).toString();
		outString(result);
	}
	/**
	 * 获取报警信息包括等级
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAlarmInfoLevelList")
	public void getAlarmInfoLevelList(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		
		String sql=" select * from BC_ALARM_TM_SET order by ct desc";
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		List<RowBase> levelTime = DataUtil.getSelectRows(sql, parms);
		int levelOne=60;
		int levelTwo=1440;
		int levelThree=1441;
		if(levelTime.size()>0){
			RowBase rt=levelTime.get(0);
			levelOne=rt.getSafeInt("LEVEL_ONE");
			levelTwo=rt.getSafeInt("LEVEL_TWO");
			levelThree=rt.getSafeInt("LEVEL_THREE");
		}
		params.put("LEVEL_ONE", levelOne+"");
		params.put("LEVEL_TWO", levelTwo+"");
		params.put("LEVEL_THREE", levelThree+"");
		List<RowBase> list = exceptionService.getAlarmInfoLevelList(params, pageInfo);
		for(int i=0;i<list.size();i++){
			RowBase r=list.get(i);
			if(r.getSafeInt("CONTINUE_TIME")<= levelOne){
				r.put("LEVEL", "1");
			}
			else if(r.getSafeInt("CONTINUE_TIME") > levelOne&&r.getSafeInt("CONTINUE_TIME") <= levelTwo){
				r.put("LEVEL", "2");
			}
			//if(r.getSafeInt("CONTINUE_TIME") > levelThree){
			else{
				r.put("LEVEL", "3");
			}	
			String value= r.getSafeString("ALARM_VALUE");
			if(value!=null&&value.indexOf("E")>0){
				BigDecimal bd = new BigDecimal(value);  
				r.put("ALARM_VALUE", bd.toPlainString());
			}
			
		}
		String result = DataUtil.listToJSONObject(list,null,pageInfo).toString();
		outString(result);
	}
	
	/**
	 * 获取最新的报警信息
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/getNewAlarmInfo")
	public void getNewAlarmInfo(HttpServletRequest resq, HttpServletResponse res){
		
		String queryTime = RequestUnit.getString("queryTime");
		
		String sql= "select t2.name stationName,t1.s_domaincaption alarmType,t2.s_domaincaption parm_name from OP_ALAR_INFO t\n" +
						"       left join data_defulatdomain t1 on t.type = t1.s_domaincode and t1.s_domainname = '报警类型'\n" + 
						"		left join data_defulatdomain t2 on t.PARAM = t2.s_domaincode and t2.s_domainname = 'MONITOR_PARAM'\n"+
						"       inner join BC_SITE_INFO t2 on t2.code = t.station_code and t2.station_category = '1' and t2.build_status = '0'\n" + 
						"       where createtime > to_date(@queryTime,'yyyy-mm-dd hh24:mi:ss') - 1/24/6 and rownum = 1";

		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("queryTime",queryTime));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		String result = DataUtil.listToJSONObject(rows,null,null).toString();
		outString(result);
	}
	
	/**
	 * 获取报警时长
	 * @return
	 */
	@RequestMapping(value = "/getLevelTime")
	public void getLevelTime(HttpServletRequest resq, HttpServletResponse res){
		String sql=" select * from BC_ALARM_TM_SET order by ct desc";
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		String result = DataUtil.listToJSONObject(rows,null,null).toString();
		outString(result);
	}
	@RequestMapping(value = "/getAlarmProcessList")
	public void getAlarmProcessList(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = exceptionService.getAlarmProcessList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list,null,pageInfo).toString();
		outString(result);
	}
	
	
	/**
	 * 获取报警信息推送情况
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/getAlarmInfoSendMessage")
	public void getAlarmInfoSendMessage(HttpServletRequest resq, HttpServletResponse res){
		String alarminfo_guid = RequestUnit.getString("alarminfo_guid");
		String sendtype = RequestUnit.getString("sendtype");		
		String sql= "select t.messagecontext,t.issend,ts.c_userealname from messagesend t"
				+ " left join messagesend_alarminfo t1 on  t1.messageguid = t.guid"
				+ " left join safe_user ts on ts.s_userid = t.messagereceiver"
				+ " where t1.alarminfoguid = '"+alarminfo_guid+"' and t.sendtype = '"+sendtype+"'";
		List<GlobalParameter> parms = new ArrayList<>();
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		String result = DataUtil.listToJSONObject(rows,null,null).toString();
		outString(result);
	}
	
	
	/**
	 * 获取报警信息日志
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAlarmLogList")
	public void getAlarmLogList(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> params = getParams();

		String sql="select t2.ALARM_VALUE,t2.UPDATETIME,t2.START_TIME,t.name as companyName,t1.name as pointName,t3.s_domaincaption as param"
				+ " ,t4.s_domaincaption as TYPE_NAME from BC_ENTERPRISE_ATTR t"
				+ " left join BC_SITE_INFO t1 on t1.wwtp_id = t.exp_no"
				+ " left join OP_ALAR_INFO t2 on  t2.station_code = t1.code"
				+ " left join DATA_DEFULATDOMAIN t3 on t3.s_domainname = 'MONITOR_PARAM' and  t3.s_domaincode = t2.param"
				+ " left join (select do.s_domaincode,do.s_domaincaption from data_defulatdomain do where do.s_domainname='报警类型') t4 on t4.s_domaincode=t2.type"
				+ " where 1=1";
		if(StringUtil.IsNotNullOrEmpty(params.get("water_type"))){
			sql+=" and t1.station_category = '"+params.get("water_type")+"'";
		}
		if(StringUtil.IsNotNullOrEmpty(params.get("station_id"))){
			sql+=" and t1.code = '"+params.get("station_id")+"'";
		}
		if(StringUtil.IsNotNullOrEmpty(params.get("alarmLogDate"))){
			sql+=" and t2.updatetime >= to_date('"+params.get("alarmLogDate")+"','yyyy-mm-dd')";
		}
		sql+= " group by t.name,t1.name,t3.s_domaincaption,t4.s_domaincaption,t2.START_TIME,t2.UPDATETIME,t2.ALARM_VALUE order by t.name";
		String title = "报警日志" + params.get("alarmLogDate");
		responseAlarmLog(params,sql,title,title);
	}
	
	/**
	 * 通用输出数据方法，对查出来的监测数据做统一包装
	 * 假如有个性化的续期，再各个方法里面单独写
	 * @param params
	 * @param result
	 * @throws Exception 
	 */
	private void responseAlarmLog(Map<String,String> params,String sql,String title,String downloadfilename) throws Exception{
		/**
		 * 输出格式
		 */
		String format = params.get("_format");
		if(format == null || format.equals("json")){
			String result = DataUtil.getPageSelectJson(sql, null);
			outString(result);
		}		
		else if(format.equals("excel")){
			List<RowBase> result =  DataUtil.getSelectRows(sql, null);
			HashMap<String, Object> excelData = new HashMap<>();
			excelData.put("dataList", result);
			excelData.put("title", title);
//			outWord(excelData, "/WasteGas/couMonthReportAir.xml", downloadfilename+".doc" );
			exportExcelWidthFreemarkerTemp("/wasteWater/alarmLog.html", null,excelData, title+".xls");
		}
	}
	/**
	 * 获取故障说明数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAlarmDescriptionList")
	public void getAlarmDescriptionList(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		String st = RequestUnit.getString("start");
		String et = RequestUnit.getString("end");
		String STATION_ID=RequestUnit.getString("STATION_ID");
		String format=RequestUnit.getString("format");
		PageInfo pageInfo = DataUtil.getPageInfo();
		String sql= " select t2.name as station_name,t1.* from bd_alarm_cause t1 left join bc_site_info t2 on t1.station_id=t2.exp_no where 1=1 ";
		if(StringUtil.IsNotNullOrEmpty(STATION_ID)){
			sql+=" and t1.STATION_ID= '"+STATION_ID+"'";
		}
		if(StringUtil.IsNotNullOrEmpty(st)){
			sql+=" and t1.st >= to_date('"+st+"','yyyy-mm-dd')";
		}
		if(StringUtil.IsNotNullOrEmpty(et)){
			sql+=" and t1.et <= to_date('"+et+"','yyyy-mm-dd')";
		}
		sql+=" order by t1.st desc";
		List<GlobalParameter> parms = new ArrayList<>();
		List<RowBase> rows = DataUtil.getPageRow(sql, parms, null, pageInfo);
		if(format.equals("json")){
			String result = DataUtil.listToJSONObject(rows,null,null).toString();
			outString(result);
		}
		else if (format.equals("excel")){
			HashMap<String, Object> excelData = new HashMap<>();
			excelData.put("dataList", rows);
			excelData.put("title", "报警说明表");
			exportExcelWidthFreemarkerTemp("/WasteGas/alarmDescription.html", null,excelData, "报警说明表"+".xls");
		}
	}
	
}
